import axios from 'axios';

const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 60000,
});

// 获取知识库列表
export const getKnowledgeBases = async (params = {}) => {
  try {
    const response = await api.get('kb/list', { params });
    return response.data;
  } catch (error) {
    console.error('获取知识库列表失败:', error);
    throw error;
  }
};

// 流式RAG查询 (核心修改)
export const ragQueryStream = async (requestData, onDataReceived, onComplete, onError) => {
  try {
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || '/api'}/chat2/rag_query_with_attention`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData)
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    if (!response.body) {
      throw new Error('ReadableStream not supported in this browser');
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let buffer = '';

    while (true) {
      const { done, value } = await reader.read();
      
      if (done) {
        if (onComplete) onComplete();
        break;
      }

      // 解码数据并添加到缓冲区
      buffer += decoder.decode(value, { stream: true });
      
      // 处理缓冲区中的完整行（SSE格式: "data: {json}\n\n"）
      const lines = buffer.split('\n');
      buffer = lines.pop() || ''; // 最后一行可能不完整，放回缓冲区

      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const dataStr = line.slice(6).trim(); // 去掉 "data: " 前缀
          
          if (dataStr) {
            try {
              const data = JSON.parse(dataStr);
              if (onDataReceived) onDataReceived(data);
            } catch (e) {
              console.error('解析SSE数据失败:', e, '原始数据:', dataStr);
              if (onError) onError(new Error('解析数据失败'));
            }
          }
        }
      }
    }
  } catch (error) {
    console.error('RAG流式请求失败:', error);
    if (onError) onError(error);
    throw error;
  }
};



